// 游戏状态和配置
const gameState = {
    isRunning: false,
    isPaused: false,
    isLevelUp: false,
    player: {
        x: 0,
        y: 0,
        speed: 5,
        health: 100,
        maxHealth: 100,
        mana: 50,
        maxMana: 50,
        damage: 10,
        exp: 0,
        level: 1,
        expToNextLevel: 100,
        gold: 0,
        kills: 0,
        direction: 'right'
    },
    enemies: [],
    bullets: [],
    chests: [],
    walls: [],
    doors: [],
    currentRoom: 0,
    wave: 1,
    enemiesRemaining: 0,
    gameMap: {
        width: 0,
        height: 0,
        roomWidth: 0,
        roomHeight: 0
    },
    controls: {
        up: false,
        down: false,
        left: false,
        right: false,
        attack: false
    },
    skills: [
        {
            name: "火球术",
            damage: 20,
            manaCost: 15,
            cooldown: 5000,
            lastUsed: 0
        },
        {
            name: "冰锥",
            damage: 15,
            manaCost: 10,
            cooldown: 3000,
            lastUsed: 0,
            slowEffect: 0.5,
            slowDuration: 2000
        },
        {
            name: "治愈",
            healAmount: 30,
            manaCost: 20,
            cooldown: 8000,
            lastUsed: 0
        }
    ]
};

// DOM 元素
const elements = {
    startScreen: document.getElementById('start-screen'),
    instructionsScreen: document.getElementById('instructions-screen'),
    gameScreen: document.getElementById('game-screen'),
    pauseScreen: document.getElementById('pause-screen'),
    gameOverScreen: document.getElementById('game-over-screen'),
    gameMap: document.getElementById('game-map'),
    player: document.getElementById('player'),
    healthFill: document.getElementById('health-fill'),
    healthText: document.getElementById('health-text'),
    manaFill: document.getElementById('mana-fill'),
    manaText: document.getElementById('mana-text'),
    expFill: document.getElementById('exp-fill'),
    expText: document.getElementById('exp-text'),
    goldDisplay: document.getElementById('gold'),
    killsDisplay: document.getElementById('kills'),
    levelUpPanel: document.getElementById('level-up-panel'),
    combatText: document.getElementById('combat-text'),
    finalScore: document.getElementById('final-score'),
    finalKills: document.getElementById('final-kills'),
    finalWave: document.getElementById('final-wave'),
    skillCooldowns: [
        document.getElementById('cooldown-1'),
        document.getElementById('cooldown-2'),
        document.getElementById('cooldown-3')
    ]
};

// 初始化函数 - 确保DOM加载完成后绑定事件
document.addEventListener('DOMContentLoaded', function() {
    // 按钮事件监听
    document.getElementById('start-btn').addEventListener('click', startGame);
    document.getElementById('how-to-play-btn').addEventListener('click', () => {
        elements.startScreen.classList.add('hidden');
        elements.instructionsScreen.classList.remove('hidden');
    });
    document.getElementById('back-btn').addEventListener('click', () => {
        elements.instructionsScreen.classList.add('hidden');
        elements.startScreen.classList.remove('hidden');
    });
    document.getElementById('pause-btn').addEventListener('click', pauseGame);
    document.getElementById('resume-btn').addEventListener('click', resumeGame);
    document.getElementById('restart-btn').addEventListener('click', restartGame);
    document.getElementById('quit-btn').addEventListener('click', quitGame);
    document.getElementById('play-again-btn').addEventListener('click', restartGame);
    document.getElementById('main-menu-btn').addEventListener('click', quitGame);

    // 升级选项事件
    document.querySelectorAll('.upgrade-option').forEach(option => {
        option.addEventListener('click', () => {
            applyUpgrade(option.dataset.type);
            elements.levelUpPanel.classList.add('hidden');
            gameState.isLevelUp = false;
        });
    });
});

// 键盘控制
function setupControls() {
    // 键盘按下
    window.addEventListener('keydown', (e) => {
        console.log('按键按下:', e.key);
        if (gameState.isPaused || gameState.isLevelUp) return;
        
        switch(e.key) {
            case 'ArrowUp':
            case 'w':
            case 'W':
                gameState.controls.up = true;
                break;
            case 'ArrowDown':
            case 's':
            case 'S':
                gameState.controls.down = true;
                break;
            case 'ArrowLeft':
            case 'a':
            case 'A':
                gameState.controls.left = true;
                gameState.player.direction = 'left';
                break;
            case 'ArrowRight':
            case 'd':
            case 'D':
                gameState.controls.right = true;
                gameState.player.direction = 'right';
                break;
            case ' ':
                if (!gameState.controls.attack) {
                    attack();
                    gameState.controls.attack = true;
                }
                break;
            case '1':
                useSkill(0);
                break;
            case '2':
                useSkill(1);
                break;
            case '3':
                useSkill(2);
                break;
        }
    });
    
    // 键盘释放
    window.addEventListener('keyup', (e) => {
        switch(e.key) {
            case 'ArrowUp':
            case 'w':
            case 'W':
                gameState.controls.up = false;
                break;
            case 'ArrowDown':
            case 's':
            case 'S':
                gameState.controls.down = false;
                break;
            case 'ArrowLeft':
            case 'a':
            case 'A':
                gameState.controls.left = false;
                break;
            case 'ArrowRight':
            case 'd':
            case 'D':
                gameState.controls.right = false;
                break;
            case ' ':
                gameState.controls.attack = false;
                break;
        }
    });
}

// 开始游戏
function startGame() {
    // 重置游戏状态
    resetGameState();
    
    // 设置游戏地图尺寸
    resizeGameMap();
    window.addEventListener('resize', resizeGameMap);
    
    // 初始化玩家位置
    gameState.player.x = gameState.gameMap.width / 2;
    gameState.player.y = gameState.gameMap.height / 2;
    updatePlayerPosition();
    
    // 生成第一个房间
    generateRoom();
    
    // 显示游戏界面
    elements.startScreen.classList.add('hidden');
    elements.gameScreen.classList.remove('hidden');
    
    // 设置控制
    setupControls();
    
    // 开始游戏循环
    gameState.isRunning = true;
    requestAnimationFrame(gameLoop);
    
    // 开始生成敌人
    spawnWave();
}

// 重置游戏状态
function resetGameState() {
    gameState.isRunning = false;
    gameState.isPaused = false;
    gameState.isLevelUp = false;
    gameState.player = {
        x: 0,
        y: 0,
        speed: 5,
        health: 100,
        maxHealth: 100,
        mana: 50,
        maxMana: 50,
        damage: 10,
        exp: 0,
        level: 1,
        expToNextLevel: 100,
        gold: 0,
        kills: 0,
        direction: 'right'
    };
    gameState.enemies = [];
    gameState.bullets = [];
    gameState.chests = [];
    gameState.walls = [];
    gameState.doors = [];
    gameState.currentRoom = 0;
    gameState.wave = 1;
    gameState.enemiesRemaining = 0;
    
    // 重置UI
    updateHUD();
}

// 调整游戏地图尺寸
function resizeGameMap() {
    gameState.gameMap.width = window.innerWidth;
    gameState.gameMap.height = window.innerHeight;
    gameState.gameMap.roomWidth = gameState.gameMap.width * 0.8;
    gameState.gameMap.roomHeight = gameState.gameMap.height * 0.8;
    
    elements.gameMap.style.width = `${gameState.gameMap.width}px`;
    elements.gameMap.style.height = `${gameState.gameMap.height}px`;
}

// 生成房间
function generateRoom() {
    // 清空当前房间元素
    clearRoom();
    
    const centerX = gameState.gameMap.width / 2;
    const centerY = gameState.gameMap.height / 2;
    const roomWidth = gameState.gameMap.roomWidth;
    const roomHeight = gameState.gameMap.roomHeight;
    
    // 创建墙壁
    // 上墙
    createWall(centerX, centerY - roomHeight/2, roomWidth, 20);
    // 下墙
    createWall(centerX, centerY + roomHeight/2, roomWidth, 20);
    // 左墙
    createWall(centerX - roomWidth/2, centerY, 20, roomHeight);
    // 右墙
    createWall(centerX + roomWidth/2, centerY, 20, roomHeight);
    
    // 创建门（随机位置）
    const doorPositions = ['top', 'bottom', 'left', 'right'];
    const doorPos = doorPositions[Math.floor(Math.random() * doorPositions.length)];
    
    switch(doorPos) {
        case 'top':
            createDoor(centerX, centerY - roomHeight/2, 40, 20);
            break;
        case 'bottom':
            createDoor(centerX, centerY + roomHeight/2, 40, 20);
            break;
        case 'left':
            createDoor(centerX - roomWidth/2, centerY, 20, 40);
            break;
        case 'right':
            createDoor(centerX + roomWidth/2, centerY, 20, 40);
            break;
    }
    
    // 随机放置宝箱
    if (Math.random() > 0.3) {
        createChest(
            centerX - roomWidth/3 + Math.random() * roomWidth * 2/3,
            centerY - roomHeight/3 + Math.random() * roomHeight * 2/3
        );
    }
}

// 创建墙壁
function createWall(x, y, width, height) {
    const wall = document.createElement('div');
    wall.className = 'wall';
    wall.style.width = `${width}px`;
    wall.style.height = `${height}px`;
    wall.style.left = `${x}px`;
    wall.style.top = `${y}px`;
    wall.style.transform = 'translate(-50%, -50%)';
    elements.gameMap.appendChild(wall);
    
    gameState.walls.push({
        element: wall,
        x, y, width, height
    });
}

// 创建门
function createDoor(x, y, width, height) {
    const door = document.createElement('div');
    door.className = 'door';
    door.style.left = `${x}px`;
    door.style.top = `${y}px`;
    door.style.transform = 'translate(-50%, -50%)';
    elements.gameMap.appendChild(door);
    
    gameState.doors.push({
        element: door,
        x, y, width, height
    });
}

// 创建宝箱
function createChest(x, y) {
    const chest = document.createElement('div');
    chest.className = 'entity chest';
    chest.style.left = `${x}px`;
    chest.style.top = `${y}px`;
    elements.gameMap.appendChild(chest);
    
    // 宝箱点击事件
    chest.addEventListener('click', () => {
        openChest(chest, x, y);
    });
    
    gameState.chests.push({
        element: chest,
        x, y
    });
}

// 打开宝箱
function openChest(chestElement, x, y) {
    // 移除宝箱
    const index = gameState.chests.findIndex(c => c.element === chestElement);
    if (index !== -1) {
        gameState.chests.splice(index, 1);
        chestElement.remove();
        
        // 随机奖励
        const goldReward = Math.floor(Math.random() * 50) + 20;
        gameState.player.gold += goldReward;
        showCombatText(x, y, `+${goldReward} 金币`, 'heal-text');
        
        // 有几率获得额外奖励
        if (Math.random() < 0.3) {
            const healAmount = Math.floor(Math.random() * 20) + 10;
            gameState.player.health = Math.min(gameState.player.health + healAmount, gameState.player.maxHealth);
            showCombatText(x, y, `+${healAmount} 生命`, 'heal-text');
            updateHUD();
        }
        
        elements.goldDisplay.textContent = gameState.player.gold;
    }
}

// 清空房间
function clearRoom() {
    // 移除墙壁
    gameState.walls.forEach(wall => wall.element.remove());
    gameState.walls = [];
    
    // 移除门
    gameState.doors.forEach(door => door.element.remove());
    gameState.doors = [];
    
    // 移除宝箱
    gameState.chests.forEach(chest => chest.element.remove());
    gameState.chests = [];
}

// 生成一波敌人
function spawnWave() {
    const enemyCount = 3 + gameState.wave * 2;
    gameState.enemiesRemaining = enemyCount;
    
    const centerX = gameState.gameMap.width / 2;
    const centerY = gameState.gameMap.height / 2;
    const roomWidth = gameState.gameMap.roomWidth;
    const roomHeight = gameState.gameMap.roomHeight;
    
    // 延迟生成敌人，不要一次性全部生成
    for (let i = 0; i < enemyCount; i++) {
        setTimeout(() => {
            if (!gameState.isRunning || gameState.isPaused) return;
            
            // 随机位置，但远离玩家
            let x, y;
            do {
                x = centerX - roomWidth/2 + 50 + Math.random() * (roomWidth - 100);
                y = centerY - roomHeight/2 + 50 + Math.random() * (roomHeight - 100);
            } while (getDistance(x, y, gameState.player.x, gameState.player.y) < 200);
            
            createEnemy(x, y);
        }, i * 800);
    }
}

// 创建敌人
function createEnemy(x, y) {
    const enemy = document.createElement('div');
    enemy.className = 'entity enemy';
    enemy.style.left = `${x}px`;
    enemy.style.top = `${y}px`;
    elements.gameMap.appendChild(enemy);
    
    // 随机敌人属性
    const enemyType = Math.random();
    let health, damage, speed, expReward;
    
    if (enemyType < 0.7) {
        // 普通敌人
        health = 30 + gameState.wave * 5;
        damage = 5 + Math.floor(gameState.wave / 2);
        speed = 2 + gameState.wave * 0.2;
        expReward = 10 + gameState.wave * 2;
    } else if (enemyType < 0.9) {
        // 精英敌人
        health = 60 + gameState.wave * 10;
        damage = 10 + gameState.wave;
        speed = 1.5 + gameState.wave * 0.15;
        expReward = 25 + gameState.wave * 5;
        enemy.style.transform = 'translate(-50%, -50%) scale(1.2)';
    } else {
        // 快速敌人
        health = 20 + gameState.wave * 3;
        damage = 3 + Math.floor(gameState.wave / 3);
        speed = 3 + gameState.wave * 0.3;
        expReward = 15 + gameState.wave * 3;
        enemy.style.transform = 'translate(-50%, -50%) scale(0.8)';
    }
    
    const enemyData = {
        element: enemy,
        x, y,
        health,
        maxHealth: health,
        damage,
        speed,
        expReward,
        lastAttack: 0,
        attackCooldown: 1500,
        slowFactor: 1,
        slowEndTime: 0
    };
    
    gameState.enemies.push(enemyData);
}

// 游戏主循环
function gameLoop(timestamp) {
    if (!gameState.isRunning || gameState.isPaused || gameState.isLevelUp) {
        requestAnimationFrame(gameLoop);
        return;
    }
    
    // 更新技能冷却
    updateSkillCooldowns();
    
    // 玩家移动
    movePlayer();
    
    // 敌人AI和移动
    moveEnemies();
    
    // 更新子弹
    updateBullets();
    
    // 检查碰撞
    checkCollisions();
    
    // 恢复魔力
    regenerateMana();
    
    // 继续循环
    requestAnimationFrame(gameLoop);
}

// 检查碰撞
function checkCollisions() {
    // 检查玩家与敌人的碰撞
    gameState.enemies.forEach((enemy, index) => {
        if (checkCollision(
            gameState.player.x, gameState.player.y, 20, 20,
            enemy.x, enemy.y, 20, 20
        )) {
            // 玩家受到伤害
            gameState.player.health -= enemy.damage;
            showCombatText(gameState.player.x, gameState.player.y, `-${enemy.damage}`, 'damage');
            
            // 检查玩家是否死亡
            if (gameState.player.health <= 0) {
                gameOver();
                return;
            }
            
            // 更新HUD
            updateHUD();
        }
    });
    
    // 检查子弹与敌人的碰撞
    gameState.bullets.forEach((bullet, bulletIndex) => {
        gameState.enemies.forEach((enemy, enemyIndex) => {
            if (checkCollision(
                bullet.x, bullet.y, 8, 8,
                enemy.x, enemy.y, 20, 20
            )) {
                // 敌人受到伤害
                enemy.health -= bullet.damage;
                showCombatText(enemy.x, enemy.y, `-${bullet.damage}`, 'damage');
                
                // 移除子弹
                removeBullet(bulletIndex);
                
                // 检查敌人是否死亡
                if (enemy.health <= 0) {
                    defeatEnemy(enemyIndex, enemy);
                }
                
                return;
            }
        });
    });
}

// 玩家移动
function movePlayer() {
    let newX = gameState.player.x;
    let newY = gameState.player.y;
    
    // 调试信息
    if (gameState.controls.up || gameState.controls.down || gameState.controls.left || gameState.controls.right) {
        console.log('=== 移动调试 ===');
        console.log('控制状态:', gameState.controls);
        console.log('当前位置:', { x: gameState.player.x, y: gameState.player.y });
    }
    
    // 根据控制方向移动
    if (gameState.controls.up) newY -= gameState.player.speed;
    if (gameState.controls.down) newY += gameState.player.speed;
    if (gameState.controls.left) newX -= gameState.player.speed;
    if (gameState.controls.right) newX += gameState.player.speed;
    
    // 边界检查
    const roomWidth = gameState.gameMap.roomWidth;
    const roomHeight = gameState.gameMap.roomHeight;
    const centerX = gameState.gameMap.width / 2;
    const centerY = gameState.gameMap.height / 2;
    
    newX = Math.max(centerX - roomWidth/2 + 20, newX);
    newX = Math.min(centerX + roomWidth/2 - 20, newX);
    newY = Math.max(centerY - roomHeight/2 + 20, newY);
    newY = Math.min(centerY + roomHeight/2 - 20, newY);
    
    // 墙壁碰撞检查
    let canMove = true;
    gameState.walls.forEach(wall => {
        if (checkCollision(
            newX, newY, 20, 20,
            wall.x, wall.y, wall.width/2, wall.height/2
        )) {
            canMove = false;
        }
    });
    
    if (canMove) {
        gameState.player.x = newX;
        gameState.player.y = newY;
        updatePlayerPosition();
    }
    
    // 检查门碰撞（只有当没有敌人时才能通过）
    if (gameState.enemiesRemaining === 0) {
        gameState.doors.forEach(door => {
            if (checkCollision(
                gameState.player.x, gameState.player.y, 20, 20,
                door.x, door.y, door.width/2, door.height/2
            )) {
                // 进入下一个房间
                nextRoom();
            }
        });
    }
}

// 更新玩家位置
function updatePlayerPosition() {
    elements.player.style.left = `${gameState.player.x}px`;
    elements.player.style.top = `${gameState.player.y}px`;
}

// 敌人移动和AI
function moveEnemies() {
    const currentTime = Date.now();
    
    gameState.enemies.forEach(enemy => {
        // 检查是否被减速
        if (enemy.slowEndTime > currentTime) {
            enemy.slowFactor = gameState.skills[1].slowEffect;
        } else {
            enemy.slowFactor = 1;
        }
        
        // 向玩家移动
        const angle = Math.atan2(
            gameState.player.y - enemy.y,
            gameState.player.x - enemy.x
        );
        
        const moveX = Math.cos(angle) * enemy.speed * enemy.slowFactor;
        const moveY = Math.sin(angle) * enemy.speed * enemy.slowFactor;
        
        // 检查墙壁碰撞
        let canMoveX = true;
        let canMoveY = true;
        
        gameState.walls.forEach(wall => {
            if (checkCollision(
                enemy.x + moveX, enemy.y, 20, 20,
                wall.x, wall.y, wall.width/2, wall.height/2
            )) {
                canMoveX = false;
            }
            
            if (checkCollision(
                enemy.x, enemy.y + moveY, 20, 20,
                wall.x, wall.y, wall.width/2, wall.height/2
            )) {
                canMoveY = false;
            }
        });
        
        if (canMoveX) enemy.x += moveX;
        if (canMoveY) enemy.y += moveY;
        
        // 更新位置
        enemy.element.style.left = `${enemy.x}px`;
        enemy.element.style.top = `${enemy.y}px`;
        
        // 攻击玩家
        if (getDistance(enemy.x, enemy.y, gameState.player.x, gameState.player.y) < 30) {
            if (currentTime - enemy.lastAttack > enemy.attackCooldown) {
                attackPlayer(enemy);
                enemy.lastAttack = currentTime;
            }
        }
    });
}

// 敌人攻击玩家
function attackPlayer(enemy) {
    gameState.player.health -= enemy.damage;
    showCombatText(
        gameState.player.x, 
        gameState.player.y - 30, 
        `-${enemy.damage}`, 
        'damage-text'
    );
    
    // 检查玩家是否死亡
    if (gameState.player.health <= 0) {
        gameState.player.health = 0;
        gameOver();
    }
    
    updateHUD();
}

// 玩家攻击
function attack() {
    // 创建子弹
    const bullet = document.createElement('div');
    bullet.className = 'entity bullet';
    elements.gameMap.appendChild(bullet);
    
    // 子弹初始位置
    let bulletX = gameState.player.x;
    let bulletY = gameState.player.y;
    
    // 根据玩家方向设置子弹初始位置
    if (gameState.player.direction === 'right') {
        bulletX += 25;
    } else {
        bulletX -= 25;
    }
    
    bullet.style.left = `${bulletX}px`;
    bullet.style.top = `${bulletY}px`;
    
    // 子弹速度和方向
    const speed = 10;
    const angle = gameState.player.direction === 'right' ? 0 : Math.PI;
    
    gameState.bullets.push({
        element: bullet,
        x: bulletX,
        y: bulletY,
        speed,
        angle,
        damage: gameState.player.damage,
        range: 300,
        distance: 0
    });
}

// 使用技能
function useSkill(index) {
    const skill = gameState.skills[index];
    const currentTime = Date.now();
    
    // 检查冷却和魔力
    if (currentTime - skill.lastUsed < skill.cooldown) {
        return;
    }
    
    if (gameState.player.mana < skill.manaCost) {
        showCombatText(
            gameState.player.x, 
            gameState.player.y - 50, 
            '魔力不足', 
            'damage-text'
        );
        return;
    }
    
    // 使用技能
    skill.lastUsed = currentTime;
    gameState.player.mana -= skill.manaCost;
    updateHUD();
    
    switch(index) {
        case 0: // 火球术
            castFireball();
            break;
        case 1: // 冰锥
            castIceLance();
            break;
        case 2: // 治愈
            castHeal();
            break;
    }
}

// 火球术
function castFireball() {
    const skill = gameState.skills[0];
    
    // 创建火球
    const fireball = document.createElement('div');
    fireball.className = 'entity bullet';
    fireball.style.backgroundColor = '#ff6b6b';
    fireball.style.width = '15px';
    fireball.style.height = '15px';
    elements.gameMap.appendChild(fireball);
    
    // 火球初始位置
    let x = gameState.player.x;
    let y = gameState.player.y;
    
    // 根据玩家方向设置初始位置
    if (gameState.player.direction === 'right') {
        x += 25;
    } else {
        x -= 25;
    }
    
    fireball.style.left = `${x}px`;
    fireball.style.top = `${y}px`;
    
    // 火球速度和方向
    const speed = 8;
    const angle = gameState.player.direction === 'right' ? 0 : Math.PI;
    
    gameState.bullets.push({
        element: fireball,
        x, y,
        speed,
        angle,
        damage: skill.damage,
        range: 500,
        distance: 0,
        isSkill: true,
        skillType: 'fireball'
    });
}

// 冰锥
function castIceLance() {
    const skill = gameState.skills[1];
    
    // 创建冰锥
    const iceLance = document.createElement('div');
    iceLance.className = 'entity bullet';
    iceLance.style.backgroundColor = '#4ecdc4';
    iceLance.style.width = '12px';
    iceLance.style.height = '12px';
    elements.gameMap.appendChild(iceLance);
    
    // 冰锥初始位置
    let x = gameState.player.x;
    let y = gameState.player.y;
    
    // 根据玩家方向设置初始位置
    if (gameState.player.direction === 'right') {
        x += 25;
    } else {
        x -= 25;
    }
    
    iceLance.style.left = `${x}px`;
    iceLance.style.top = `${y}px`;
    
    // 冰锥速度和方向
    const speed = 12;
    const angle = gameState.player.direction === 'right' ? 0 : Math.PI;
    
    gameState.bullets.push({
        element: iceLance,
        x, y,
        speed,
        angle,
        damage: skill.damage,
        range: 400,
        distance: 0,
        isSkill: true,
        skillType: 'ice'
    });
}

// 治愈
function castHeal() {
    const skill = gameState.skills[2];
    gameState.player.health = Math.min(
        gameState.player.health + skill.healAmount, 
        gameState.player.maxHealth
    );
    
    showCombatText(
        gameState.player.x, 
        gameState.player.y - 30, 
        `+${skill.healAmount}`, 
        'heal-text'
    );
    
    updateHUD();
}

// 更新技能冷却
function updateSkillCooldowns() {
    const currentTime = Date.now();
    
    gameState.skills.forEach((skill, index) => {
        const cooldownEl = elements.skillCooldowns[index];
        const remaining = skill.lastUsed + skill.cooldown - currentTime;
        
        if (remaining > 0) {
            const percentage = remaining / skill.cooldown;
            cooldownEl.style.clipPath = `polygon(0 0, 100% 0, 100% ${percentage * 100}%, 0 100%)`;
        } else {
            cooldownEl.style.clipPath = 'polygon(0 0, 100% 0, 100% 0, 0 0)';
        }
    });
}

// 更新子弹
function updateBullets() {
    // 遍历子弹并更新位置
    for (let i = gameState.bullets.length - 1; i >= 0; i--) {
        const bullet = gameState.bullets[i];
        
        // 更新位置
        bullet.x += Math.cos(bullet.angle) * bullet.speed;
        bullet.y += Math.sin(bullet.angle) * bullet.speed;
        bullet.distance += bullet.speed;
        
        // 更新DOM位置
        bullet.element.style.left = `${bullet.x}px`;
        bullet.element.style.top = `${bullet.y}px`;
        
        // 检查是否超出范围或碰到墙壁
        if (bullet.distance > bullet.range) {
            removeBullet(i);
            continue;
        }
        
        let hitWall = false;
        gameState.walls.forEach(wall => {
            if (checkCollision(
                bullet.x, bullet.y, 5, 5,
                wall.x, wall.y, wall.width/2, wall.height/2
            )) {
                hitWall = true;
            }
        });
        
        if (hitWall) {
            removeBullet(i);
            continue;
        }
        
        // 检查是否击中敌人
        for (let j = gameState.enemies.length - 1; j >= 0; j--) {
            const enemy = gameState.enemies[j];
            
            if (getDistance(bullet.x, bullet.y, enemy.x, enemy.y) < 25) {
                // 敌人受伤
                enemy.health -= bullet.damage;
                showCombatText(enemy.x, enemy.y - 20, `-${bullet.damage}`, 'damage-text');
                
                // 冰锥技能效果
                if (bullet.isSkill && bullet.skillType === 'ice') {
                    enemy.slowEndTime = Date.now() + gameState.skills[1].slowDuration;
                }
                
                // 检查敌人是否死亡
                if (enemy.health <= 0) {
                    defeatEnemy(j, enemy);
                }
                
                // 移除子弹（技能子弹可以穿透）
                if (!bullet.isSkill || bullet.skillType !== 'fireball') {
                    removeBullet(i);
                }
                
                break;
            }
        }
    }
}

// 移除子弹
function removeBullet(index) {
    if (gameState.bullets[index]) {
        gameState.bullets[index].element.remove();
        gameState.bullets.splice(index, 1);
    }
}

// 击败敌人
function defeatEnemy(index, enemy) {
    // 显示得分
    showCombatText(enemy.x, enemy.y, `+${enemy.expReward} 经验`, 'heal-text');
    
    // 更新玩家状态
    gameState.player.exp += enemy.expReward;
    gameState.player.kills++;
    gameState.enemiesRemaining--;
    
    // 更新UI
    elements.killsDisplay.textContent = gameState.player.kills;
    
    // 通知 uni-app 击败敌人
    if (typeof notifyGameEvent === 'function') {
        notifyGameEvent('enemyDefeated', {
            exp: enemy.expReward,
            kills: gameState.player.kills,
            level: gameState.player.level,
            gameType: 'roguelikeToy'
        });
    }
    
    // 检查是否升级
    checkLevelUp();
    
    // 移除敌人
    enemy.element.remove();
    gameState.enemies.splice(index, 1);
    
    // 检查是否所有敌人都被击败
    if (gameState.enemiesRemaining === 0) {
        // 显示门
        gameState.doors.forEach(door => {
            door.element.style.opacity = '1';
        });
    }
    
    updateHUD();
}

// 检查升级
function checkLevelUp() {
    while (gameState.player.exp >= gameState.player.expToNextLevel) {
        // 升级
        gameState.player.level++;
        gameState.player.exp -= gameState.player.expToNextLevel;
        gameState.player.expToNextLevel = Math.floor(gameState.player.expToNextLevel * 1.5);
        
        // 显示升级面板
        elements.levelUpPanel.classList.remove('hidden');
        gameState.isLevelUp = true;
        
        updateHUD();
    }
}

// 应用升级
function applyUpgrade(type) {
    switch(type) {
        case 'health':
            gameState.player.maxHealth += 20;
            gameState.player.health = gameState.player.maxHealth;
            showCombatText(
                gameState.player.x, 
                gameState.player.y - 30, 
                '生命提升!', 
                'heal-text'
            );
            break;
        case 'damage':
            gameState.player.damage += 5;
            showCombatText(
                gameState.player.x, 
                gameState.player.y - 30, 
                '攻击提升!', 
                'heal-text'
            );
            break;
        case 'mana':
            gameState.player.maxMana += 10;
            gameState.player.mana = gameState.player.maxMana;
            showCombatText(
                gameState.player.x, 
                gameState.player.y - 30, 
                '魔力提升!', 
                'heal-text'
            );
            break;
    }
    
    updateHUD();
}

// 魔力恢复
function regenerateMana() {
    if (gameState.player.mana < gameState.player.maxMana) {
        gameState.player.mana += 0.02;
        if (gameState.player.mana > gameState.player.maxMana) {
            gameState.player.mana = gameState.player.maxMana;
        }
        updateHUD();
    }
}

// 检查碰撞
function checkCollision(x1, y1, w1, h1, x2, y2, w2, h2) {
    return (
        x1 - w1 < x2 + w2 &&
        x1 + w1 > x2 - w2 &&
        y1 - h1 < y2 + h2 &&
        y1 + h1 > y2 - h2
    );
}

// 计算距离
function getDistance(x1, y1, x2, y2) {
    const dx = x2 - x1;
    const dy = y2 - y1;
    return Math.sqrt(dx * dx + dy * dy);
}

// 显示战斗文字
function showCombatText(x, y, text, className) {
    const textElement = elements.combatText.cloneNode(true);
    textElement.textContent = text;
    textElement.className = `combat-text ${className}`;
    textElement.style.left = `${x}px`;
    textElement.style.top = `${y}px`;
    textElement.style.opacity = '1';
    
    document.body.appendChild(textElement);
    
    // 动画效果
    let position = 0;
    let opacity = 1;
    
    const animation = setInterval(() => {
        position -= 2;
        opacity -= 0.05;
        
        textElement.style.transform = `translate(-50%, ${position}px)`;
        textElement.style.opacity = opacity;
        
        if (opacity <= 0) {
            clearInterval(animation);
            textElement.remove();
        }
    }, 20);
}

// 更新HUD
function updateHUD() {
    // 生命值
    const healthPercent = (gameState.player.health / gameState.player.maxHealth) * 100;
    elements.healthFill.style.width = `${healthPercent}%`;
    elements.healthText.textContent = `${Math.floor(gameState.player.health)}/${gameState.player.maxHealth}`;
    
    // 魔力值
    const manaPercent = (gameState.player.mana / gameState.player.maxMana) * 100;
    elements.manaFill.style.width = `${manaPercent}%`;
    elements.manaText.textContent = `${Math.floor(gameState.player.mana)}/${gameState.player.maxMana}`;
    
    // 经验值
    const expPercent = (gameState.player.exp / gameState.player.expToNextLevel) * 100;
    elements.expFill.style.width = `${expPercent}%`;
    elements.expText.textContent = `Lv.${gameState.player.level} ${gameState.player.exp}/${gameState.player.expToNextLevel}`;
    
    // 金币和击杀数
    elements.goldDisplay.textContent = gameState.player.gold;
    elements.killsDisplay.textContent = gameState.player.kills;
}

// 进入下一个房间
function nextRoom() {
    gameState.currentRoom++;
    gameState.wave++;
    
    // 生成新房间
    generateRoom();
    
    // 移动玩家到新房间中心
    gameState.player.x = gameState.gameMap.width / 2;
    gameState.player.y = gameState.gameMap.height / 2;
    updatePlayerPosition();
    
    // 生成新一波敌人
    spawnWave();
}

// 暂停游戏
function pauseGame() {
    gameState.isPaused = true;
    elements.gameScreen.classList.add('hidden');
    elements.pauseScreen.classList.remove('hidden');
}

// 恢复游戏
function resumeGame() {
    gameState.isPaused = false;
    elements.pauseScreen.classList.add('hidden');
    elements.gameScreen.classList.remove('hidden');
    requestAnimationFrame(gameLoop);
}

// 重新开始游戏
function restartGame() {
    // 清除所有实体
    gameState.enemies.forEach(enemy => enemy.element.remove());
    gameState.bullets.forEach(bullet => bullet.element.remove());
    
    // 隐藏所有屏幕
    elements.pauseScreen.classList.add('hidden');
    elements.gameOverScreen.classList.add('hidden');
    
    // 开始新游戏
    startGame();
}

// 退出游戏
function quitGame() {
    gameState.isRunning = false;
    
    // 清除所有实体
    gameState.enemies.forEach(enemy => enemy.element.remove());
    gameState.bullets.forEach(bullet => bullet.element.remove());
    clearRoom();
    
    // 显示开始屏幕
    elements.gameScreen.classList.add('hidden');
    elements.pauseScreen.classList.add('hidden');
    elements.gameOverScreen.classList.add('hidden');
    elements.startScreen.classList.remove('hidden');
}

// 游戏结束
function gameOver() {
    gameState.isRunning = false;
    
    // 更新结束界面
    elements.finalScore.textContent = gameState.player.gold;
    elements.finalKills.textContent = gameState.player.kills;
    elements.finalWave.textContent = gameState.wave;
    
    // 通知 uni-app 游戏结束
    if (typeof notifyGameEvent === 'function') {
        notifyGameEvent('gameEnd', {
            score: gameState.player.gold,
            kills: gameState.player.kills,
            wave: gameState.wave,
            level: gameState.player.level,
            gameType: 'roguelikeToy'
        });
    }
    
    // 显示结束屏幕
    elements.gameScreen.classList.add('hidden');
    elements.gameOverScreen.classList.remove('hidden');
}
    